import { Component, OnInit, ViewChild } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { format, subDays, differenceInHours } from 'date-fns';
import { NzModalService } from 'ng-zorro-antd/modal';
import { storagePurchaseStateArrs, storageDeliveryMethodArrs } from '../../xstorage-manage-pipes/storage-manage-z.pipe';
import { CommonService } from '../../../../services-common/common.service';
import { PermissionService } from '../../../../service/permission.service';
import { StorageCommonService } from '../../xstorage-manage-services/storage-common.service';
import { StoragePurchaseManageService } from '../../xstorage-manage-services/storage-purchase-manage.service';

@Component({
  selector: 'app-storage-purchase-list',
  templateUrl: './storage-purchase-list.component.html',
  styleUrls: ['./storage-purchase-list.component.scss']
})
export class StoragePurchaseListComponent implements OnInit {
  // 路由缓存恢复时
  static updateCache: any = null;
  @ViewChild('followUpRef') followUpRef: any;

  searchOptions = [
    { type: 1, labelText: '采购单号', valueKey: 'purchaseNumber', value: '' },
    { type: 1, labelText: '包含商品', valueKey: 'whGood', value: '', placeholder: '编码/69码/名称' },
    {
      type: 2,
      labelText: '状态',
      valueKey: 'state',
      value: [],
      multiple: true,
      notTostr: false,
      selectBindKey: { key: 'value', label: 'label' },
      selectOptions: [...storagePurchaseStateArrs]
    },
    { type: 3, labelText: '新建时间', valueKey: ['beginTime', 'endTime'], value: [], isTimeSelect: true },
    { type: 3, labelText: '结案时间', valueKey: ['beginClosingTime', 'endClosingTime'], value: [], isTimeSelect: true }
  ];
  searchParams: any = {};

  supplierOptions: any[] = []; // 供应商Options

  tableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 20,
    total: 0
  };

  // 跟进 Modal
  initParams: any = {
    type: 1, // type 1、采购 2、SN 3、入库单 4、出库单
    relationInformation: ''
  };

  /**
   * 审核 Modal
   * ----------------------------------------------------------------
   */
  isExamineVisible = false;
  examineLoading = false;
  examineItem: any = {};
  auditOpinion: string = '';

  constructor(
    private msg: NzMessageService,
    private fb: FormBuilder,
    private modal: NzModalService,
    private commonService: CommonService,
    public permission: PermissionService,
    private storageCommonService: StorageCommonService,
    private services: StoragePurchaseManageService
  ) { }

  ngOnInit(): void {
    this.loadSupplierList();

    StoragePurchaseListComponent.updateCache = () => {
      this.loadSupplierList();
      this.loadTable();
    }
  }

  // 查询供应商
  async loadSupplierList() {
    const res: any = await this.commonService.getSupplierList();
    // 状态为正常de
    this.supplierOptions = res.filter((item: any) => item.state === 1);
    // this.setSearchOption(res, 'type');
  }

  async loadTable() {
    let params = {
      ...this.searchParams,
      page: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    this.tableParams.loading = true;
    const {code, data, message}: any = await this.services.getPurchaseList(params);
    this.tableParams.loading = false;
    // return

    if (code === 0) {
      this.tableParams.tableData = data.records || [];
      this.tableParams.total = data.total || 0;
    } else {
      this.msg.error(message);
    }
  }

  queryResetData(params: any) {
    this.searchParams = params;
    this.tableParams.page = 1;
    this.loadTable();
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }

  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  /**
   * 删除
   * @param item 
   * ----------------------------------------------------------------
   */
  async deleteItem(item: any) {
    let params = {
      id: item.id
    }
    const { code, message }: any = await this.services.deletePurchaseItem(params);

    if (code === 0) {
      this.msg.success('删除成功');
      this.loadTable();
    } else {
      this.msg.error(message);
    }
  }

  /**
   * 提交审核(1) | 反审核(6)
   * @param item 
   * ----------------------------------------------------------------
   */
  async submitReview(item: any, type: number) {
    let params = {
      id: item.id,
      state: type
    }
    const { code, message }: any = await this.services.examinePurchaseItem(params);

    if (code === 0) {
      this.msg.success('操作成功');
      this.loadTable();
    } else {
      this.msg.error(message);
    }
  }
  
  /**
   * ----------------------------------------------------------------
   * 审核
   * ----------------------------------------------------------------
   */
  showExamineModal(item: any) {
    this.examineItem = item;
    this.auditOpinion = '';
    this.isExamineVisible = true;
  }

  async subExamine(type: number) {
    if (type === 5 && this.commonService.isEmpty(this.auditOpinion)) {
      this.msg.warning('请输入审核意见');
      return
    }

    let params = {
      id: this.examineItem.id,
      state: type, // 1 提交审核 2 进行中 3已结案 4已作废 5审核不通过 6反审核
      note: this.auditOpinion
    }
    this.examineLoading = true;
    const res: any = await this.services.examinePurchaseItem(params);
    this.examineLoading = false;

    if (res.code === 0) {
      this.isExamineVisible = false;
      this.msg.success('操作成功');
      this.loadTable();
    } else {
      this.msg.error(res.message);
    }
  }

  /**
   * 结案
   * ----------------------------------------------------------------
   */
  closeCase(item: any) {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '该操作不可逆，结案后该单将彻底不可操作，是否继续?',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let params = {
          id: item.id,
          state: 3, // 1 提交审核 2 进行中 3已结案 4已作废 5审核不通过 6反审核
          note: ''
        }
        const res: any = await this.services.examinePurchaseItem(params);
    
        if (res.code === 0) {
          this.msg.success('操作成功');
          this.loadTable();
        } else {
          this.msg.error(res.message);
        }
      },
      nzCancelText: '取消'
    });
  }

  /**
   * other
   * ----------------------------------------------------------------
   */
  setSearchOption(array: Array<any>, val: string) {
    let temIndex = this.searchOptions.findIndex((item: any) => item.valueKey === val);
    this.searchOptions[temIndex].selectOptions = array || [];
  }

  // Filter Text
  filterText(arrs: Array<any>, keyVal: any, idKey: string) {
    let tempObjs: any = {};
    if (arrs.length) {
      tempObjs = arrs.find(item => item[idKey] == keyVal);
    }

    return tempObjs?.name || '-';
  }

  /**
   * 不等于 {{ 结案 }} 状态
   * 用约定时间 - 当前时间
   * 日期在当前日期之前的话，则用红色字体(超过72小时)
   * 日期在当前日期3天内的话，则用黄色字体(72小时内)
   * @param item 
   */
  filterTimeColor(item: any) {
    let nowTime = new Date();
    let appointTime = !this.commonService.isEmpty(item.deliveryTime) ? new Date(item.deliveryTime) : 0;
    let diffNum = differenceInHours(appointTime, nowTime);

    if (item.deliveryTime && item.state !== 3) {
      if (diffNum >= 0 && diffNum < 72) {
        return '#FF9900';
      } else if (diffNum < 0) {
        return '#F56C6C';
      } else {
        return '';
      }
    } else {
      return '';
    }
  }

  // 跟进
  showFollowModal(item: any) {
    this.initParams.relationInformation = item.id;
    this.followUpRef.isModelVisible = true;
  }
}
